-- contrary to behavior descriptors, behaviors are goal trees and not goal DAGs

require("Goal")

Behavior = class("Behavior")

Behavior.rootGoalName = "Root"

---

function Behavior:initialize(behaviorDescriptor)
	
	self.rootGoal = false
	self.mind = false
	self.variables = {}

	if behaviorDescriptor
	then
		assert(behaviorDescriptor.Root, "Behavior descriptor need a Root goal")
		
		self.behaviorDescriptor = behaviorDescriptor
		self.effectors = {}
		self.rootGoal = self:createGoal(behaviorDescriptor.Root, Behavior.rootGoalName, self)
	end
end

---

function Behavior:createGoal(goalDescriptor, name, parent)

	local goal = Goal:new(name, parent)
	goal.behavior = self
	
	
	-- causes
	
	if goalDescriptor.causes
	then		
		goal.causes = Sentence:new(goalDescriptor.causes)
	end
	
	
	-- effects
	
	if goalDescriptor.effects
	then
		goal.effects = Sentence:new(goalDescriptor.effects)
		
		self.effectors[#self.effectors + 1] = goal
	end
	
	
	-- other data
	
	if goalDescriptor.updateVariables
	then
		assert(type(goalDescriptor.updateVariables) == "function")
		
		goal.updateVariablesFunction = goalDescriptor.updateVariables
	end
	
	goal.constraint = goalDescriptor.constraint
	
	
	-- sub goals
	
	if goalDescriptor.subGoals
	then
		for i, subGoalName in ipairs(goalDescriptor.subGoals)
		do
			assert(
				self.behaviorDescriptor[subGoalName], 
				"Goal " .. subGoalName .. " not found in behavior descriptor"
			)
			
			goal.subGoals[subGoalName] = self:createGoal(self.behaviorDescriptor[subGoalName], subGoalName, goal)
		end
	end
	
	return goal
end

---

function Behavior:updateVariables()

	self.variables.me = self.mind
	self.variables.myType = self.mind.type
	self.variables.myName = self.mind.name
	self.variables.myBodyType = self.mind.body.type
	self.variables.myBodyName = self.mind.body.name
	self.variables.myBody = self.mind.body
	self.variables.myPockets = self.mind.body.pockets

	if self.mind.body:isPropertyCollasped("CurrentContainer")
	then
		self.variables.myLocation = self.mind.body:getCollapsedProperty("CurrentContainer")
	else
		self.variables.myLocation = false
	end
	
	self.rootGoal:updateVariables()
end

